using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Core : MonoBehaviour
{
    public Rigidbody2D Rb { get; private set; }
    public int FacingDirection { get; private set; }
    public Player player { get; set; }

    public float moveSpeed = 6;
    private Vector2 workSpace;

    public WeaponPickup newWeapon { get; set; }
    public event Action<WeaponPickup> UpdateWeapon;

    private void Awake()
    {
        Rb = GetComponentInParent<Rigidbody2D>();
        FacingDirection = 1;
    }

    public void SetVelocity(float velocity, Vector2 vector2)
    {
        workSpace = vector2.normalized * velocity;
        Rb.velocity = workSpace;
    }

    public void CheckIfShouldFlip(int xInput)
    {
        if (xInput != 0 && xInput != FacingDirection)
        {
            Flip();
        }
    }

    public void Flip()
    {
        FacingDirection *= -1;
        Rb.transform.localScale = new Vector3(FacingDirection, 1, 1);
    }

    public void TriggerInteraction()
    {
        if (newWeapon == null)
        {
            return;
        }
        UpdateWeapon?.Invoke(newWeapon);
    }

    public void HandleWeaponChanged(WeaponPickup pickup)
    {
        Instantiate(player.weapon.pickupPrefab, pickup.transform.position, Quaternion.identity);
        Destroy(pickup.gameObject);
        Destroy(player.transform.GetChild(1).gameObject);
        var newWeapon = Instantiate(pickup.weaponPrefab, player.transform);
        player.weapon = newWeapon.GetComponentInChildren<Weapon>();
        player.AttackState = new PlayerAttackState(player, player.StateMachine, "attack", player.weapon);
        player.weapon.SetCore(this);
        player.weapon.InitWeapon();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.TryGetComponent(out WeaponPickup weaponPickup))
        {
            newWeapon = weaponPickup;
        }
    }

    public void LogicUpdate()
    {

    }
}
